<?php

namespace App\CLI;

use Forxx\console\CLIRunner;
use Forxx\console\CConsole;

class CDSQLHelper extends CLIRunner{
	
	public function exec_action()
	{	
		$args = func_get_args();
        if(count($args) == 2)
        {
            $template_file  = $args[0];
            $template_out_file  = $args[1];
        }
        else
        {
            $template_file  = CConsole::prompt("input the sql file name","demo.tpl.sql");
            $template_out_file  = CConsole::prompt("output the sql file name","demo.out.sql");
        }

		$path = dirname(__FILE__).DIRECTORY_SEPARATOR.$template_file;
		$out_path = dirname(__FILE__).DIRECTORY_SEPARATOR.$template_out_file;
		if(!file_exists($path))
		{
			CConsole::print_line("sql file [ $path ] not exists!");
			return;
		}
		$template_sql = "";
		$template_db_sql = "";
		
		$file_handle = fopen($path, "r");
		while (!feof($file_handle)) {
			$buffer = fgets($file_handle, 4096);
			$buffer = trim($buffer);
			if(empty($buffer))
			{
				continue;
			}
			if(strtolower(substr($buffer,0,4)) === "use ")
			{
				$template_db_sql .= $buffer."\n\n";
			}
			else 
			{
				$template_sql .= $buffer."\n";
			}
		}
		fclose($file_handle);		
		
		$file_handle = fopen($out_path, "w+");
		
		if(empty($template_sql))
		{
			CConsole::print_line("can not be empty!");
			return;
		}	
		$db_num = 10;
		$table_num = 10;
				
		for ($db_id = 0 ;$db_id < $db_num ; $db_id++ ) {			
			$db_current_sql = str_replace("{{db_index}}", strval($db_id), $template_sql);
			$db_output_sql = str_replace("{{db_index}}", strval($db_id), $template_db_sql);
			fwrite($file_handle,"\n". $db_output_sql);
            CConsole::print_line("execute at {{process}}% ...",["{{process}}"=> number_format( ( $db_id / $db_num  ) *100,2) ]);
            for ($table_id =0 ; $table_id < $table_num ; $table_id ++) {
				$table_current_sql =  str_replace("{{table_index}}", strval($table_id), $db_current_sql);
				fwrite($file_handle, $table_current_sql);
			}
		}
        fwrite($file_handle,"\n");
		fclose($file_handle);
		CConsole::print_line("completed !");
		return;
		
	}

}

?>